package com.test4;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.worktool.RestExecutor;
import net.sourceforge.tess4j.ITessAPI;
import net.sourceforge.tess4j.TessAPI;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    static RestTemplate restTemplate = RestExecutor.buildNew();

    private static final String env = "prod";

    private static final String sourcImgPath = "G:/ocr/img";

    private static final String ocrPath = "G:/TesseractGit/tessdata";

    public static void main(String[] args) throws IOException {

        // 设置Tesseract OCR引擎的数据路径，这里需要指定tessdata目录的路径
        //System.setProperty("tess4j.datapath", "path/to/tessdata"); // 替换为您的tessdata目录路径

//        System.out.println(getqrCode("gh_e5e5ce9ee7b4"));
//
//        System.out.println(getqrCode("123456"));

        Test test = new Test();
        test.savaGid();


    }

    public void savaGid(){
        try {

            File imageFile = new File(sourcImgPath); // 替换为您的图片文件路径

            File[] files = imageFile.listFiles();

            Tesseract tesseract = new Tesseract();
            //tesseract.setOcrEngineMode(ITessAPI.TessOcrEngineMode.OEM_TESSERACT_LSTM_COMBINED);
            tesseract.setDatapath(ocrPath); // 替换为您的tessdata目录路径




            Set<OcrExcel> se = new HashSet<>();
            for(int i=0;i<files.length;i++){

                File file = files[i];

                if(file.isDirectory()){
                    continue;
                }

//测试代码
//                g2d(ImageIO.read(file),file);
//                break;

                OcrExcel ocrExcel = new OcrExcel();

                //解析中文
                tesseract.setLanguage("eng+chi_sim");
                Rectangle rect = getRec(false);


                String name = tesseract.doOCR(file,rect);
                if(StringUtils.isNotBlank(name)){
                    name = name.replaceAll(" ","").replaceAll("\n","");
                }

                ocrExcel.setName(name);
                //解析英文
                tesseract.setLanguage("eng+chi_sim");
                rect = getRec(true);

                String ghid = tesseract.doOCR(file,rect);
                if(StringUtils.isNotBlank(name)){
                    ghid = ghid.replaceAll(" ","").replaceAll("\n","");
                }
                ocrExcel.setGhid(ghid);
                se.add(ocrExcel);

                String nameNew = name+".png";
                if(!file.getName().equals(nameNew)){
                    File fileNew = new File(imageFile.getPath()+"/"+nameNew);
                    file.renameTo(fileNew);
                }
                System.out.println("识别数据："+ocrExcel);
            }
            List<OcrExcel> data = opGhid(se);

            EasyExcel.write("G:/savaGid1.xlsx", OcrExcel.class).sheet("数据").doWrite(data);
            System.out.println("over：---------------------");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("OCR识别出错: " + e.getMessage());
        }
    }



    private static Rectangle getRec(boolean ghid){
        int x = 184; // 左上角 x 坐标
        int y = 235; // 左上角 y 坐标
        int width = 700; // 矩形宽度
        int height = 50; // 矩形高度

        if(ghid){
            y = y+50;
            x = x+110;
            width = 245;
        }
        return new Rectangle(x,y,width,height);
    }



    // 转换指定颜色为黑色方法
    private static BufferedImage convertColorToBlack(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();

        Color targetColor = new Color(136, 136, 136);

        // 遍历图像的每个像素
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                Color pixelColor = new Color(rgb);

                // 如果像素颜色与目标颜色匹配，则将其设置为黑色
                if (pixelColor.equals(targetColor)) {
                    image.setRGB(x, y, new Color(16, 16, 16).getRGB()); // 设置为黑色
                }
            }
        }
        return image;
    }

    // 灰度增强处理方法
    private static BufferedImage enhanceGrayscale(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage enhancedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 增强参数，可以根据需要进行调整
        double contrastFactor = 1.5; // 对比度增强因子
        double brightnessFactor = 50.0; // 亮度增强因子

        // 循环遍历图像像素
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                int gray = (rgb >> 16) & 0xFF; // 提取红色通道作为灰度值

                // 增强灰度值
                int newGray = (int) (gray * contrastFactor + brightnessFactor);
                newGray = Math.min(255, Math.max(0, newGray)); // 确保在0到255的范围内

                // 设置新像素颜色
                int newRgb = (newGray << 16) | (newGray << 8) | newGray; // 灰度图像
                enhancedImage.setRGB(x, y, newRgb);
            }
        }

        return enhancedImage;
    }


    private static boolean getqrCode(String gid){
        String url = "https://open.weixin.qq.com/qr/code?username=";
        String path = url+ gid;

        try {
            URL uri = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) uri.openConnection();

            // 设置请求方法为HEAD，这样只获取响应头信息而不下载图片内容
            //connection.setRequestMethod("HEAD");

            // 获取Content-Type头信息
            String contentType = connection.getHeaderField("Content-type");

            if (contentType != null && contentType.startsWith("image/")) {
                return true;
            }

            return false;

        } catch (IOException e) {
            System.out.println("发生异常，可能是网络问题或无效的URL。");
            e.printStackTrace();
            return false;
        }

    }


    // 锐化处理方法
    private static BufferedImage sharpenImage(BufferedImage image) {
        // 创建锐化内核
        float[] sharpeningKernel = {
                -1, -1, -1,
                -1, 9, -1,
                -1, -1, -1
        };

        Kernel kernel = new Kernel(3, 3, sharpeningKernel);
        BufferedImageOp sharpenOp = new ConvolveOp(kernel);

        BufferedImage sharpenedImage = sharpenOp.filter(image, null);

        return sharpenedImage;
    }


    private static void g2d(BufferedImage image,File file){
        // 创建 Graphics2D 对象以在图像上进行绘制
        Graphics2D g2d = image.createGraphics();


        Rectangle rectangle = getRec(true);

        // 设置矩形的边框颜色
        g2d.setColor(Color.RED);

        // 在图像上绘制矩形
        g2d.drawRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
        // 释放资源
        g2d.dispose();


        // 保存修改后的图像
        File outputImageFile = new File("G:/gd2/"+file.getName());


        // 目标颜色（RGB值为136, 136, 136）

        image = convertColorToBlack(image);


        try {
            ImageIO.write(image, "png", outputImageFile);
            System.err.println("保存图片");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<OcrExcel> opGhid(Collection<OcrExcel> arr){
        List<OcrExcel> data = new LinkedList<>();
        for(OcrExcel ocrExcel:arr){
            if(!setGid(ocrExcel)){
                data.add(ocrExcel);
            }
        }
        return data;
    }

    private static boolean setGid(OcrExcel ocrExcel){

        if(Objects.isNull(ocrExcel.getGhid())||ocrExcel.getGhid().length()!=15){
            //设置msg
            ocrExcel.setDesc("gid识别有误");
            return false;
        }

        if(!getqrCode(ocrExcel.getGhid())){
            ocrExcel.setDesc("非图片");
            return false;
        }

        if(!restSavaGid(env,ocrExcel)){
            //ocrExcel.setDesc("保存图片失败");
            return false;
        }

        return true;
        //// 调用接口

    }

    private static boolean restSavaGid(String env,OcrExcel param){
        String path="/admin/saveGhId";
        String url = "http://tmp.s.weshaketv.com/cnag_hb_api";
        if ("prod".equals(env)){
            url = "https://mp.s.weshaketv.com/cnag_hb_api";
        }
        url = StrUtil.format("{}/{}",url,path);


        try {
            JSONObject params = new JSONObject();
            params.put("corp_name",param.getName());
            params.put("gh_id",param.getGhid());

            JSONObject result = restTemplate.postForObject(url,params,JSONObject.class);

            if(result.getIntValue("errCode")!=0){
                param.setDesc(result.getString("errMsg"));
            }
            return result.getIntValue("errCode")==0;

        }catch (Exception e){
            param.setDesc("保存图片失败");
            e.printStackTrace();
            return false;
        }

    }

}
